package com.dengcj.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dengchunjie
 * @Description: Http接口工具类
 * @date 2022/2/1709:21
 */
public class CjApiUtil {


    public static String jsonEmptyKeyValidate(JSONObject jsonObject, List<String> validateKeys){
        List<String> emptyKeyList = new ArrayList<>();
        for(String key : validateKeys){
            String val = jsonObject.getStr(key);

            if(StrUtil.isBlank(val)){
                emptyKeyList.add(key+"为空");
            }
        }

        if(emptyKeyList.size() > 0){
            return "参数校验失败："+emptyKeyList.stream().collect(Collectors.joining(","))+"。";
        }

        return "";
    }

    /**
     * json非空校验
     * @param jsonObject
     * @param exceptKeys 不需要校验的字段
     * @return
     */
    public static String jsonEmptyValidate(JSONObject jsonObject, List<String> exceptKeys){

        if(exceptKeys != null) {
            for (String exceptKey : exceptKeys) {
                jsonObject.remove(exceptKey);
            }
        }

        List<String> emptyKeyList = new ArrayList<>();
        Set<String> keys = jsonObject.keySet();
        for(String key : keys){
            String val = jsonObject.getStr(key);

            if(StrUtil.isBlank(val)){
                emptyKeyList.add(key+"为空");
            }
        }

        if(emptyKeyList.size() > 0){
            return "参数校验失败："+emptyKeyList.stream().collect(Collectors.joining(","));
        }

        return "";
    }


    public static String jsonEmptyValidate(String jsonStr, List<String> exceptKeys){
        JSONObject jsonObject = new JSONObject(jsonStr);

        return jsonEmptyValidate(jsonObject, exceptKeys);
    }

    /**
     * json非空校验
     * @param jsonStr
     * @param exceptKeys 不需要校验的字段
     * @return
     */
    public static String jsonEmptyValidate(String jsonStr, String... exceptKeys){
        return jsonEmptyValidate(jsonStr, Arrays.asList(exceptKeys));
    }

    /**
     * json非空校验
     * @param jsonObject
     * @param exceptKeys 不需要校验的字段
     * @return
     */
    public static String jsonEmptyValidate(JSONObject jsonObject, String... exceptKeys){
        return jsonEmptyValidate(jsonObject, Arrays.asList(exceptKeys));
    }

    /**
     * json非空校验
     * @param jsonStr
     * @return
     */
    public static String jsonEmptyValidate(String jsonStr){
        return jsonEmptyValidate(jsonStr, (List<String>) null);
    }
}
